package com.desk.copyfile.utils;

import com.desk.copyfile.main.MyConfigHolder;
import com.desk.copyfile.main.MyConfigProperties;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 具体用于复制文件 并且判断文件名是否复核实现工具类
 */
@Component
public abstract class CopyFilesUtils {

    public static void copyFilesToOtherPath(Date startDateSource, Date endDateSource, List<String> selectedPathNameList, JTextArea resultArea) {
        MyConfigProperties myConfigProperties = MyConfigHolder.getMyConfigProperties();
        Map<String, String[]> allOptionsMap = myConfigProperties.getAllOptionsMap();
        for (String selectPath : selectedPathNameList) {
            Path directory = Paths.get(allOptionsMap.get(selectPath)[0]);
            // 日期转换
            ZonedDateTime zdtStart = startDateSource.toInstant().atZone(ZoneId.systemDefault());
            ZonedDateTime zdtEnd = endDateSource.toInstant().atZone(ZoneId.systemDefault());
            LocalDate startDate = LocalDate.of(zdtStart.getYear(), zdtStart.getMonth(), zdtStart.getDayOfMonth()); // 替换为你的开始日期
            LocalDate endDate = LocalDate.of(zdtEnd.getYear(), zdtEnd.getMonth(), zdtEnd.getDayOfMonth()); // 替换为你的结束日期
            try {
                if (!Files.exists(directory)) {
                    resultArea.append("\n文件夹不存在：" + directory);
                    continue;
                }
                Files.walk(directory)
                        .filter(Files::isRegularFile)
                        .forEach(path -> {
                            String fileName = path.getFileName().toString();
                            if (fileName.endsWith(".zip")) {
                                fileName = fileName.substring(0, fileName.length() - ".zip".length());
                            }
                            // 使用正则表达式匹配文件名中的日期格式
                            String regex = "\\b(\\d{4}-\\d{2}-\\d{2})|(\\d{8})\\b";

                            Pattern pattern = Pattern.compile(regex);
                            Matcher matcher = pattern.matcher(fileName);

                            if (matcher.find()) {
                                if (isValidDate(matcher.group())) {

                                    String dateStr = matcher.group(0).replace("-", "").replace("_", "");

                                    // 尝试解析日期字符串
                                    try {
                                        LocalDate fileDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyyMMdd"));
                                        // 检查日期是否在指定范围内
                                        if (!fileDate.isBefore(startDate) && !fileDate.isAfter(endDate)) {
                                            // 复制文件到指定路径
                                            if (copyFileToTargetDir(path.toString(), allOptionsMap.get(selectPath)[1])) {
                                                resultArea.append("\nFile copied successfully!: " + path);
                                            } else {
                                                resultArea.append("\nFile copy failed!: " + path);
                                            }
                                            ;
                                        }
                                    } catch (DateTimeException e) {
                                        // 解析失败，不是有效的日期格式
                                        resultArea.append("\nFile dataFomat Error: " + path);
                                    }
                                } else {
                                    System.out.println("文件名中包含的日期格式不正确：" + fileName);
                                    System.out.println("matcher.group()：" + matcher.group());
                                }
                            }
                        });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean copyFileToTargetDir(String sourceFilePath, String targetDirPath) {
        Path sourceFile = Paths.get(sourceFilePath); // 源文件路径
        Path targetDir = Paths.get(targetDirPath); // 目标目录路径
        Path targetFile = targetDir.resolve(sourceFile.getFileName()); // 目标文件路径（在目标目录中）
        Boolean result = Boolean.FALSE;
        try {
            // 检查源文件是否存在
            if (Files.exists(sourceFile) && Files.isRegularFile(sourceFile)) {
                // 检查目标目录是否存在，如果不存在则创建
                if (!Files.exists(targetDir)) {
                    Files.createDirectories(targetDir);
                }

                // 复制文件到目标目录
                Files.copy(sourceFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
                result = Boolean.TRUE;
                System.out.println("File copied successfully!");
            } else {
                System.out.println("Source file does not exist or is not a regular file.");
            }
        } catch (IOException e) {
            System.err.println("An error occurred while copying the file." + e.getMessage());
            // e.printStackTrace();
        }
        return result;
    }

    private static boolean isValidDate(String potentialDate) {
        try {
            // 尝试将字符串解析为日期
            if (potentialDate.contains("-")) {
                // 处理yyyy-MM-dd格式
                java.time.LocalDate.parse(potentialDate, java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            } else {
                // 处理yyyymmdd格式
                java.time.LocalDate.parse(potentialDate, java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
            }
            return true; // 如果解析成功，则返回true
        } catch (java.time.format.DateTimeParseException e) {
            return false; // 如果解析失败，则返回false
        }
    }
}
